<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ref, reactive, onMounted, computed, h } from 'vue'
import { CustomSearch } from '@/components/CustomSearch'
import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { FormSchema } from '@/components/Form'
import { ElTag, ElMessage, ElButton, ElDialog, ElIcon } from 'element-plus'
import { Icon } from '@/components/Icon'
import { ChatSidebarPanel } from '@/components/IntelligentChat'
import type { ComponentPublicInstance } from 'vue'
import { abnorCategOptions, deregAttrTypeOptions, ecCategOptions, custClsOptions } from '@/dicts'
import { getAbnormalOrderStatsZg, updateQuadAbnorRntHndl } from '@/api/electricityAbnormal'
import { DIFY_API_V1_URL, DIFY_API_KEY_changjing3 } from '@/constants/dify'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

interface ChatSidebarInstance extends ComponentPublicInstance {
  openDrawer: () => void
  closeDrawer: () => void
}

interface IResponse<T> {
  code: number
  data: T
  message: string
}

interface TableRow {
  id: string
  [key: string]: any
}

const { t } = useI18n()

// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData, setValues } = searchMethods

const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'expYm',
    label: '量费年月',
    component: 'DatePicker',
    componentProps: {
      type: 'monthrange',
      valueFormat: 'YYYYMM',
      startPlaceholder: '开始年月',
      endPlaceholder: '结束年月',
      size: 'default', // 添加size属性，可选值：large/default/small
      style: { width: '60%' }, // 添加style属性控制宽度
      value: ['202504', '202504']
    }
  },
  // {
  //   field: 'custCls',
  //   label: '客户分类',
  //   component: 'Select',
  //   componentProps: {
  //     placeholder: '请选择客户分类',
  //     options: custClsOptions,
  //     multiple: true,
  //     collapseTags: true,
  //     collapseTagsTooltip: true,
  //     clearable: true
  //   }
  // },
  {
    field: 'deregAttrCls',
    label: '市场化属性分类',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择市场化属性分类',
      props: {
        checkStrictly: false,
        emitPath: false,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: deregAttrTypeOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'ecCateg',
    label: '用电类别',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择用电类别',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: ecCategOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'abnorCateg',
    label: '初步研判异常类型',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择初步研判异常类型',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: abnorCategOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  }
])

// 获取上个月的起止日期（YYYYMM格式）
const getPreviousMonthRange = () => {
  const currentDate = dayjs()
  const previousMonth = currentDate.subtract(1, 'month')
  const previousMonthStr = previousMonth.format('YYYYMM')
  return [previousMonthStr, previousMonthStr]
}

// 使用useTable钩子
const { tableRegister, tableMethods, tableState } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    try {
      // 获取搜索表单数据
      const formData = await getFormData()
      console.log('搜索条件:', formData)
      if (formData.ecCateg && formData.ecCateg.length !== 0) {
        formData.ecCateg = formData.ecCateg.flat()
      } else {
        formData.ecCateg = []
      }
      // 调用后端API获取数据
      const requestParams = {
        startExpYm: formData.expYm?.[0], //
        endExpYm: formData.expYm?.[1], //
        mgtOrgName: formData.mgtOrgName,
        abnorTypeList: formData.abnorCateg?.map((item) => item[0] || ''), //
        abnorCategList:
          formData.abnorCateg?.length > 0 ? formData.abnorCateg?.map((item) => item[1] || '') : [], //
        // custCls: formData.custCls, //
        custNo: formData.custNo, // 用户编号
        deregAttrCls: formData.deregAttrCls, // 市场化属性分类
        ecCateg: formData.ecCateg, // 用电类别
        rectStat: '01', // 整改状态
        pageSize: tableState.pageSize.value,
        pageNum: tableState.currentPage.value
      }

      console.log('请求参数:', requestParams)

      // 使用真实API调用代替模拟数据
      const response = await getAbnormalOrderStatsZg(requestParams)
      console.log('API响应数据:', response)

      // 处理响应数据
      if (response && response.data) {
        // 检查响应数据结构并规范化数据格式
        let list: any[] = []
        let total = 0

        // 提取数据列表
        const responseData = response.data

        if (Array.isArray(responseData)) {
          // 如果data本身是数组
          list = responseData
          total = (response as any).total || responseData.length || 0
        } else if (typeof responseData === 'object') {
          // 如果data是对象
          if (responseData.list && Array.isArray(responseData.list)) {
            list = responseData.list
            total = responseData.total || responseData.list.length || 0
          } else if (responseData.records && Array.isArray(responseData.records)) {
            list = responseData.records
            total = responseData.total || responseData.records.length || 0
          } else if (responseData.rows && Array.isArray(responseData.rows)) {
            list = responseData.rows
            total = responseData.total || responseData.rows.length || 0
          }

          // 如果上面没有找到total，尝试从其他常见字段中查找
          if (!total && responseData.totalCount) {
            total = responseData.totalCount
          } else if (!total && responseData.count) {
            total = responseData.count
          }
        }

        return {
          list,
          total
        }
      }

      return {
        list: [],
        total: 0
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败，请重试')
      return {
        list: [],
        total: 0
      }
    }
  }
})

// 从useTable中解构获取数据和状态
const { dataList, total, currentPage, pageSize, loading } = tableState
const { refresh } = tableMethods

// 多选相关数据
const selectedRows = ref<any[]>([])

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 表格列配置
const columns = reactive<TableColumn[]>([
  {
    field: '',
    type: 'selection', // 多选列
    width: 60,
    selection: true
  },
  {
    field: 'index',
    type: 'index', // 序号列
    label: '序号',
    width: 60,
    fixed: 'left'
  },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    minWidth: 150
  },
  {
    field: 'expYm',
    label: '量费年月',
    width: 100
  },
  {
    field: 'planNo',
    label: '计划编号',
    minWidth: 120
  },
  {
    field: 'bilgUnitNo',
    label: '核算包编号',
    minWidth: 120
  },
  {
    field: 'custNo',
    label: '用户编号',
    width: 120
  },
  {
    field: 'abnorType',
    label: '初步研判异常类别',
    width: 150
  },
  {
    field: 'abnorCateg',
    label: '初步研判异常类型',
    width: 150
  },
  {
    field: 'abnorDtlInfo',
    label: '初步研判异常说明',
    width: 150
  },
  {
    field: 'quadAbnorType',
    label: '二次研判异常类别',
    width: 150
  },
  {
    field: 'quadAbnorCateg',
    label: '二次研判异常类型',
    width: 150
  },
  {
    field: 'quadAbnorDtlInfo',
    label: '二次研判异常说明',
    width: 150
  },
  {
    field: 'rectStat',
    label: '整改状态',
    width: 130,
    hidden: true,
    formatter: (row) => {
      // 状态码与名称的映射
      const statusNameMap = {
        '00': '未处理',
        '01': '未处理',
        '02': '处理中',
        '03': '已处理',
        '04': '无需处理'
      }

      // 状态名称与样式类型的映射
      const statusStyleMap = {
        未处理: 'danger',
        处理中: 'warning',
        已处理: 'success',
        无需处理: 'info'
      }

      // 获取状态名称
      const statusName = statusNameMap[row.rectStat] || '未知状态'
      // 获取对应的样式类型
      const styleType = statusStyleMap[statusName] || 'info'

      return h(ElTag, { type: styleType }, () => statusName)
    }
  },

  {
    field: 'tSettleQty',
    label: '总结算量',
    minWidth: 120
  },
  {
    field: 'tSettleExp',
    label: '总结算费',
    minWidth: 120
  },
  {
    field: 'action',
    label: '操作',
    width: 150,
    fixed: 'right',
    slots: {
      default: ({ row }) => {
        return [
          h(
            ElButton,
            {
              type: 'primary',
              link: true,
              onClick: () => viewDetails(row)
            },
            () => '查看详情'
          )
        ]
      }
    }
  }
])

// 详情弹窗相关参数
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

// 查看详情
const viewDetails = (row) => {
  console.log('查看详情:', row)
  // ElMessage.success('查看详情功能待实现')
  currentDetail.value = {
    ...row
  }
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

// AI聊天相关
const chatSidebarRef = ref<ChatSidebarInstance | null>(null)
const aiInputs = ref({})
// 添加AI分析结果状态
const aiAnalysisResult = ref<any>(null)
// 添加details内容状态
const detailsContent = ref<any>(null)

// 处理AI会话完成
const handleAiFinish = (result: any) => {
  console.log('AI会话结束:', result)
  if (result.extractedJson) {
    // 保存提取的JSON数据
    aiAnalysisResult.value = result.extractedJson
    console.log('量费核算分析结果:', aiAnalysisResult.value)

    ElMessage.success('已提取分析结果')
  }

  // 处理details内容
  if (result.detailsContent) {
    detailsContent.value = result.detailsContent
    console.log('提取的details内容:', detailsContent.value)
    // 根据提取的数据进行相应处理
    submitAnalysisToBackend()
  }
}

// 处理details提取事件
const handleDetailsExtracted = (details: any) => {
  detailsContent.value = details
  console.log('从AI对话中提取的details内容:', details)
}

// 转换JSON数据为变量并提交到后端
const submissionData = reactive<any>({})
const submitAnalysisToBackend = async () => {
  if (!detailsContent.value) {
    ElMessage.warning('没有可提交的分析结果')
    return
  }

  try {
    // 识别后的数据 - 确保是数组格式
    const afterRecognitionData = JSON.parse(detailsContent.value)
    console.log('识别后的数据:======》', afterRecognitionData)

    submissionData.value = afterRecognitionData.map((originalItem) => {
      return {
        abnorRntHndlId: originalItem.abnorRntHndlId,
        // 将 abnormal_level1.name 赋值给 abnorType
        quadAbnorType: originalItem.abnormal_level1?.name || originalItem.abnorType,
        // 将 abnormal_level2.name 赋值给 abnorCateg
        quadAbnorCateg: originalItem.abnormal_level2?.name || originalItem.abnorCateg,
        // 将 root_cause 赋值给 abnorDtlInfo
        quadAbnorDtlInfo: originalItem.root_cause || originalItem.abnorDtlInfo
      }
    })
    console.log('提交处理后的分析结果到后端的数据:======》', submissionData.value)
    // 调用异常识别API
    const res = (await updateQuadAbnorRntHndl(submissionData.value)) as IResponse<any>
    if (res && res.code === 200) {
      ElMessage.success('提交成功')
      refresh()
    }
  } catch (error) {
    console.error('提交分析结果失败:', error)
    ElMessage.error('提交分析结果失败，请重试')
  }
}

// 搜索处理
const handleSearch = async () => {
  refresh()
}

// 重置搜索
const handleReset = async () => {
  refresh()
}
const { setProps } = tableMethods
// 初始化
onMounted(() => {
  // 设置固定表格高度 437.8
  setProps({
    height: 438
  })
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)
    // 统一设置所有表单项的大小和宽度
    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })

    // 设置量费年月默认值为上个月
    setValues({
      expYm: getPreviousMonthRange()
    })
    console.log('设置默认量费年月:', getPreviousMonthRange())

    // 使用setTimeout确保默认值已经被应用
    setTimeout(() => {
      // 初始化表格数据
      refresh()
    }, 100)
  } else {
    // 如果searchRef为空，仍然需要刷新数据
    refresh()
  }
})

// 处理ChatSidebarPanel的before-open事件
const handleBeforeOpen = () => {
  // 检查是否选中了至少一条数据
  // if (selectedRows.value.length === 0) {
  //   ElMessage.warning('请至少选择一条需识别的数据！')
  //   // 阻止打开聊天面板
  //   return false
  // }
  chatSidebarRef.value?.openDrawer()
  // 准备传递给AI助手的结构化数据
  const structuredData = selectedRows.value.map((row) => {
    // 确保返回原始行的完整拷贝，不丢失任何字段
    const { abnorType, abnorCateg, abnorDtlInfo, ...restData } = { ...row }
    return restData
  })

  // 设置AI输入数据
  aiInputs.value = {
    table_data: JSON.stringify(structuredData)
  }

  return true
}

// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}
</script>

<template>
  <ContentWrap title="量费核算二次研判">
    <!-- 搜索区域 -->
    <CustomSearch
      ref="searchRef"
      :schema="schema"
      label-width="130px"
      :layout="'bottom'"
      :button-position="'right'"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="table-toolbar">
      <div>总计：{{ total }}条数据</div>
    </div>

    <!-- 表格区域 -->
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :loading="loading"
      :data="dataList"
      :height="450"
      :fit="true"
      :columns="columns"
      row-key=""
      :pagination="{
        total: total,
        pageSizes: [10, 20, 50, 100],
        background: true
      }"
      style="
        --el-table-border-color: #cdd7d5;
        --el-table-text-color: #171717;
        --el-table-header-text-color: #585858;
      "
      :header-cell-style="{
        background: '#e5f5f3', // 背景色
        color: '#585858' // 文字颜色
      }"
      :row-style="tableRowStyle"
      @register="tableRegister"
      @refresh="refresh"
      @selection-change="handleSelectionChange"
    />

    <!-- 侧边栏聊天组件 -->
    <ChatSidebarPanel
      ref="chatSidebarRef"
      :api-key="DIFY_API_KEY_changjing3"
      :api-base="DIFY_API_V1_URL"
      :inputs="aiInputs"
      title="量费核算智能分析"
      placeholder="请输入您想了解的问题..."
      welcome-message="您好！我是量费核算智能分析助手。我可以帮您分析电费异常问题，提供解决方案。请问有什么需要帮助的吗？"
      @message-end="handleAiFinish"
      @details-extracted="handleDetailsExtracted"
      @before-open="handleBeforeOpen"
      :show-float-button="true"
    />

    <!-- 不要AI分析结果区域 -->
  </ContentWrap>

  <!-- 详情弹窗 -->
  <ElDialog
    v-model="detailDialogVisible"
    title="详情"
    width="70%"
    :before-close="closeDetailDialog"
    destroy-on-close
    class="detail-dialog"
    style=""
  >
    <div class="detail-container">
      <div class="detail-section">
        <div class="detail-title">异常信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">初步研判异常类别：</div>
            <div class="detail-value">{{ currentDetail?.abnorCateg }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">初步研判异常类型：</div>
            <div class="detail-value">{{ currentDetail?.abnorType }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">初步研判异常说明：</div>
            <div class="detail-value">{{ currentDetail?.abnorDtlInfo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">二次研判异常类别：</div>
            <div class="detail-value">{{ currentDetail?.quadAbnorCateg }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">二次研判异常类型：</div>
            <div class="detail-value">{{ currentDetail?.quadAbnorType }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">二次研判异常说明：</div>
            <div class="detail-value">{{ currentDetail?.quadAbnorDtlInfo }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">算费信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">量费年月：</div>
            <div class="detail-value">{{ currentDetail?.expYm }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">计划编号：</div>
            <div class="detail-value">{{ currentDetail?.planNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">核算包编号：</div>
            <div class="detail-value">{{ currentDetail?.bilgUnitNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">本次抄见量：</div>
            <div class="detail-value">{{ currentDetail?.thisMrQty }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">总结算量：</div>
            <div class="detail-value">{{ currentDetail?.tSettleQty }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">总结算费：</div>
            <div class="detail-value">{{ currentDetail?.tSettleExp }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">本次抄见量</div>
        <div class="reading-table-container">
          <table class="reading-table">
            <thead>
              <tr>
                <td class="table-label">示数类型</td>
                <td v-if="currentDetail?.zxygReadType" class="table-header">正向有功（总）</td>
                <td v-if="currentDetail?.zxygjfReadType" class="table-header">正向有功（尖峰）</td>
                <td v-if="currentDetail?.zxygfReadType" class="table-header">正向有功（峰）</td>
                <td v-if="currentDetail?.zxyggReadType" class="table-header">正向有功（谷）</td>
                <td v-if="currentDetail?.zxygpReadType" class="table-header">正向有功（平）</td>
                <td v-if="currentDetail?.zxwgReadType" class="table-header">正向无功（总）</td>
                <td v-if="currentDetail?.wgReadType" class="table-header">无功（Q4象限）</td>
                <td v-if="currentDetail?.zdxlReadType" class="table-header">最大需量</td>
                <td v-if="currentDetail?.fxwgReadType" class="table-header">反向无功（总）</td>
                <td v-if="currentDetail?.fxygReadType" class="table-header">反向有功（总）</td>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td class="table-label">抄见电量</td>
                <td v-if="currentDetail?.zxygReadType" class="table-cell">{{
                  currentDetail?.zxygReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxygjfReadType" class="table-cell">{{
                  currentDetail?.zxygjfReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxygfReadType" class="table-cell">{{
                  currentDetail?.zxygfReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxyggReadType" class="table-cell">{{
                  currentDetail?.zxyggReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxygpReadType" class="table-cell">{{
                  currentDetail?.zxygpReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxwgReadType" class="table-cell">{{
                  currentDetail?.zxwgReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.wgReadType" class="table-cell">{{
                  currentDetail?.wgReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zdxlReadType" class="table-cell">{{
                  currentDetail?.zdxlReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.fxwgReadType" class="table-cell">{{
                  currentDetail?.fxwgReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.fxygReadType" class="table-cell">{{
                  currentDetail?.fxygReadTypeNameDl || '-'
                }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">基础档案信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">管理单位：</div>
            <div class="detail-value">{{ currentDetail?.mgtOrgName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用户编号：</div>
            <div class="detail-value">{{ currentDetail?.custNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用户名称：</div>
            <div class="detail-value">{{ currentDetail?.custName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">客户分类：</div>
            <div class="detail-value">{{ currentDetail?.custClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">市场化属性分类：</div>
            <div class="detail-value">{{ currentDetail?.deregAttrClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">合同容量：</div>
            <div class="detail-value">{{ currentDetail?.ctrtCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">运行容量：</div>
            <div class="detail-value">{{ currentDetail?.runCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用电类别：</div>
            <div class="detail-value">{{ currentDetail?.ecCategName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">行业分类：</div>
            <div class="detail-value">{{ currentDetail?.indClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">价格码：</div>
            <div class="detail-value">{{ currentDetail?.prcCode }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">定价策略类型：</div>
            <div class="detail-value">{{ currentDetail?.prcStTypeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">基本电费计算方式：</div>
            <div class="detail-value">{{ currentDetail?.becCalcModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">功率因数考核标准：</div>
            <div class="detail-value">{{ currentDetail?.pfStdName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">功率因数考核方式：</div>
            <div class="detail-value">{{ currentDetail?.pfEvalModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">电压等级：</div>
            <div class="detail-value">{{ currentDetail?.voltage }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">计量点信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">安装点状态：</div>
            <div class="detail-value">{{ currentDetail?.instStatName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点编号：</div>
            <div class="detail-value">{{ currentDetail?.instNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点容量：</div>
            <div class="detail-value">{{ currentDetail?.instCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">计量方式：</div>
            <div class="detail-value">{{ currentDetail?.meterModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点用途分类：</div>
            <div class="detail-value">{{ currentDetail?.instUsageClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">能源计算方式：</div>
            <div class="detail-value">{{ currentDetail?.eCalcModeCodeName }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section-end">
        <div class="detail-title">设备信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">表计设备编号：</div>
            <div class="detail-value">{{ currentDetail?.mrDevNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">表计类型：</div>
            <div class="detail-value">{{ currentDetail?.devTypeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">损耗编号：</div>
            <div class="detail-value">{{ currentDetail?.lossNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">变损计算方式：</div>
            <div class="detail-value">{{ currentDetail?.lossAlgFlagName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">调压设备编码：</div>
            <div class="detail-value">{{ currentDetail?.adjDevNo }}</div>
          </div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style lang="scss" scoped>
.el-button {
  margin-left: 8px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 详情弹窗样式 */
.detail-container {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  background-color: #f2f2f2;
  padding: 26px 6px 26px 26px;
}

.detail-section {
  padding: 6px;
  border-bottom: 1px solid #999;
}

.detail-section-end {
  padding: 6px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 4px;
  margin-bottom: 6px;
}

.detail-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 0 0 0 70px;
}

.detail-item {
  width: 33.333%;
  min-height: 30px;
  display: flex;
  padding: 10px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  flex: 0.5;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

/* AI分析结果区域样式 */
.analysis-result-container {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  h3 {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .result-section {
    padding: 10px;
    background-color: #f2f2f2;
    border-radius: 4px;
    overflow-x: auto;
  }

  .json-result {
    white-space: pre;
    font-family: monospace;
  }
}

/* 示数类型表格样式 */
.reading-table-container {
  padding: 0 0 0 70px;
  margin-top: 10px;
}

.reading-table {
  width: 100%;
  border-collapse: collapse;
  /* background-color: #fff; */
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

.reading-table thead {
  /* background-color: #f5f7fa; */
}

.reading-table .table-label {
  /* background-color: #e6f7ff; */
  font-weight: bold;
  color: #303133;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  min-width: 80px;
}

.reading-table .table-header {
  /* background-color: #f5f7fa; */
  font-weight: bold;
  color: #606266;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  font-size: 13px;
  white-space: nowrap;
}

.reading-table .table-cell {
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  color: #303133;
  white-space: nowrap;
}
</style>
